﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using TyMES.Model.Record;
using TyMES.ViewModel.Record.MaterialBindRecordVMs;
using TyMES.Model;
using Microsoft.AspNetCore.SignalR;
using TyMES.MidWare;
using Microsoft.Extensions.Logging;
using TyMES.Services;
using TyMES.PassStationCommunication;
using TyMES.Communication.Request;
using TyMES.Model.BaseInformation;

namespace TyMES.Record.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.MaterialBindRecord")]
    [ApiController]
    [Route("/api/Record/MaterialBindRecord")]
    public partial class MaterialBindRecordController : BaseApiController
    {
        private readonly IHubContext<InverseControlHub> inverseControl;
        private readonly ILogger logger;
        private PassStationService passStationService;
        public MaterialBindRecordController(IHubContext<InverseControlHub> inverseControl, ILogger<MaterialBindRecordController> logger, PassStationService passStationService)
        {
            this.inverseControl = inverseControl;
            this.logger = logger;
            this.passStationService = passStationService;
           
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<MaterialBindRecordVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(MaterialBindRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(MaterialBindRecordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }
                

        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(MaterialBindRecordBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<MaterialBindRecordBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<MaterialBindRecordImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(MaterialBindRecordImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }

        [HttpPost("PegTZData")]
        public async Task<CSTJRequest.GetTZInfoResponse> PegTZData(CSTJRequest.GetTZInfoRequest res)
        {
            try
            {
                var CSFirstStation = DC.Set<CustomConfig>().Where(x => x.customProperty == "CSFirstStationCode").First().propertyValue;
                var CSFirstStation_Manual = DC.Set<CustomConfig>().Where(x => x.customProperty == "CSFirstStationCode-manual").First().propertyValue;
                var PegZPTZSN = DC.Set<MaterialBindRecord>().Where(x => x.SnNumber == res.SN &&( x.StationCode == CSFirstStation||x.StationCode== CSFirstStation_Manual)).OrderByDescending(x=>x.ID).FirstOrDefault();
                if (PegZPTZSN == null)
                {
                    return new CSTJRequest.GetTZInfoResponse { Success = false, Mesg = $"SN[{res.SN}]在测试线上线未执行电机装配段SN虚拟料号绑定" };
                }

                var TZFirstStation = DC.Set<CustomConfig>().Where(x => x.customProperty == "TZFirstStationCode").First().propertyValue;

                var TZMaterialBindRecord = DC.Set<MaterialBindRecord>().Where(x => x.StationCode == TZFirstStation && x.SnNumber == PegZPTZSN.AssemblyMaterialSn).FirstOrDefault();
                if (TZMaterialBindRecord == null)
                {
                    return new CSTJRequest.GetTZInfoResponse { Success = false, Mesg = $"未查询到装配段SN[{PegZPTZSN.AssemblyMaterialSn}]上线绑定电机记录" };
                }
                return new CSTJRequest.GetTZInfoResponse { Success = true, TZCode = TZMaterialBindRecord.AssemblyMaterialSn };

            }
            catch (Exception ex)
            {
                return new CSTJRequest.GetTZInfoResponse { Success = false, Mesg = ex.Message };
            }

        }




    }
}